package com.shanghaionstar.carmanage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.adapter.OnstarFlowCommonAdapter;
import com.shanghaionstar.carmanage.model.FlowItem;
import com.shanghaionstar.swipe.SwipeActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mengting Lu
 * @ClassName: FlowCalCulationActivity
 * @Description: 流量计算器页面：在4G页面点击流量计算器按钮跳转到此页面
 * @date 2015年8月6日 上午9:49:53
 */
@ContentView(R.layout.car_manage_activity_flow_caculator)
public class FlowCalCulationActivity extends SwipeActivity implements SeekBar.OnSeekBarChangeListener {

    /******
     * 流量、单位
     ****/
    @FindViewById
    private TextView tv_flowUnit, tv_flowTotal;
    /********
     * 设备数量
     ****/
    @FindViewById
    TextView tv_device_count;

    @FindViewById
    ViewAnimator seek_va;
    /*********
     * 网格
     ******/
    @FindViewById
    GridView content_gv;

    private int num_social, num_vidio, num_music, num_comp, num_read, num_gupiao, num_email, num_yingyong;

    /********
     * 各种滑动条
     ******/
    @FindViewById
    private SeekBar sb_social, sb_video, sb_music, sb_comp, sb_read, sb_gupiao, sb_email, sb_yingyong;

    private int totalRemainDays;
    private int count = 0;
    private int selectDevicePosition = 0;
    private int curPos = -1;

    private List<FlowItem> items = new ArrayList<>();
    private TextView curTv;
    private TextView dayTv;

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        setSeekListeners();
        initFlowItems();
        setUpFlowAdapter();
    }

    /**
     * 监听seekbar滑动事件
     */
    private void setSeekListeners() {
        sb_social.setOnSeekBarChangeListener(this);
        sb_video.setOnSeekBarChangeListener(this);
        sb_music.setOnSeekBarChangeListener(this);
        sb_comp.setOnSeekBarChangeListener(this);
        sb_read.setOnSeekBarChangeListener(this);
        sb_gupiao.setOnSeekBarChangeListener(this);
        sb_email.setOnSeekBarChangeListener(this);
        sb_yingyong.setOnSeekBarChangeListener(this);
    }

    /**
     * 初始化数据
     */
    private void initFlowItems() {
        String[] titles = getResources().getStringArray(R.array.flow_items);
        String[] hours = getResources().getStringArray(R.array.flow_pre_hour);
        String[] days = getResources().getStringArray(R.array.flow_pre_day);
        items.clear();
        for (int i = 0; i < titles.length; i++) {
            FlowItem item = new FlowItem();
            item.title = titles[i];
            item.perHour = hours[i];
            item.perDay = days[i];
            items.add(item);
        }
    }

    private void setUpFlowAdapter() {
        final OnstarFlowCommonAdapter mAdapter1 = new OnstarFlowCommonAdapter(this, items);
        content_gv.setAdapter(mAdapter1);
        content_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 8) return;
                mAdapter1.setClickPosition(position);
                if (seek_va.getVisibility() == View.GONE)
                    seek_va.setVisibility(View.VISIBLE);
                seek_va.setDisplayedChild(position);
                mAdapter1.notifyDataSetChanged();
                curPos = position;
                curTv = (TextView) view.findViewById(R.id.pre_value_tv);
                if (position == 6)
                    dayTv = (TextView) view.findViewById(R.id.pre_day_tv);
            }
        });
    }

    @OnClick(R.id.device_count)
    public void OnClick(View view) {
        showDeviceCountDialog();
    }

    /**
     * 显示设备数选择框
     */
    private void showDeviceCountDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setSingleChoiceItems(R.array.data_device_count, selectDevicePosition,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String[] items = getResources().getStringArray(R.array.data_device_count);
                        tv_device_count.setText(items[which]);
                        selectDevicePosition = which;
                        dialog.dismiss();
                        calculateTotalOnstarPackage();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onProgressChanged(SeekBar seekbar, int arg1, boolean arg2) {
        switch (seekbar.getId()) {
            case R.id.sb_email:
                if (seekbar.getProgress() >= 180) {
                    sb_email.setProgress(200);
                }
                break;
            case R.id.sb_yingyong:
                if (seekbar.getProgress() >= 20) {
                    sb_yingyong.setProgress(20);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekbar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekbar) {
        String value = String.valueOf(seekbar.getProgress());
        curTv.setText(value);
        switch (seekbar.getId()) {
            case R.id.sb_social:
                doOnTrackSocial();
                break;
            case R.id.sb_video:
                doOnTrackVideo();
                break;
            case R.id.sb_music:
                doOnTrackMusic();
                break;
            case R.id.sb_comp:
                doOnTrackComp();
                break;
            case R.id.sb_read:
                doOnTrackRead();
                break;
            case R.id.sb_gupiao:
                doOnTrackStock();
                break;
            case R.id.sb_email:
                doOnTrackEmail(seekbar);
                break;
            case R.id.sb_yingyong:
                doOnTrackYingYong(seekbar);
                break;
            default:
                break;
        }
        calculateTotalOnstarPackage();
    }

    private void doOnTrackSocial() {
        num_social = sb_social.getProgress() * 2;// 社交软件
    }

    private void doOnTrackVideo() {
        num_vidio = sb_video.getProgress() * 120;// 在线视频
    }

    private void doOnTrackMusic() {
        num_music = sb_music.getProgress() * 5;// 在线音乐
    }

    private void doOnTrackComp() {
        num_comp = sb_comp.getProgress() * 4;// 在线游戏
    }

    private void doOnTrackRead() {
        num_read = sb_read.getProgress() * 2;// 上网阅读
    }

    private void doOnTrackStock() {
        num_gupiao = sb_gupiao.getProgress() * 4;// 查看股票
    }

    private void doOnTrackEmail(SeekBar seekBar) {// 查看email
        int progress = calcaulatorPoint(sb_email.getProgress());
        if (seekBar.getProgress() >= 180)
            sb_email.setProgress(200);
        if (progress >= 200)
            progress = 200;
        num_email = progress;
        if (progress >= 100) {
            String emailValue = getString(R.string.ft_two);
            curTv.setText(progress + "");
            if (dayTv != null)
                dayTv.setText(emailValue);
        } else {
            String emailValue = getString(R.string.ft);
            curTv.setText(progress + "");
            if (dayTv != null)
                dayTv.setText(emailValue);
        }
    }

    private void doOnTrackYingYong(SeekBar seekBar) {// 下载应用
        int progress = sb_yingyong.getProgress();
        if (progress >= 20) {
            num_yingyong = 20 * 6;
        } else {
            num_yingyong = progress * 6;
        }
        if (seekBar.getProgress() >= 20) {
            sb_yingyong.setProgress(20);
        }
    }

    /**
     * 这个方法是将所有的流量放到流量框里
     */
    private void calculateTotalOnstarPackage() {
        count = Integer.parseInt(tv_device_count.getText().toString());
        int totalRemainDays = (num_social + num_vidio + num_music + num_comp + num_read + num_gupiao + num_yingyong)
                * 30 * count + (num_email * 300) / 1024 * 30;
        if (totalRemainDays < 1024) {
            java.text.DecimalFormat df = new java.text.DecimalFormat("####.##");
            String totalFlow = df.format(totalRemainDays / 1.0);
            tv_flowUnit.setText(R.string.package_flow_mb);
            tv_flowTotal.setText(totalFlow);

        } else {
            //将所有软件的所用流量加起来
            totalRemainDays = (num_social + num_vidio + num_music + num_comp + num_read + num_gupiao + num_yingyong)
                    * 30 * count + (num_email * 300) / 1024 * 30;
            float totals = totalRemainDays / 1024f;

            calculateTotalOnstarPackage(totals);
        }
    }

    /**
     * 收发电子邮件 设置每滑动一下间距就是20
     */
    private int calcaulatorPoint(int progress) {
        int pro = 0;
        if (progress == 0) {
            pro = 0;
        } else if (progress >= 180) {
            pro = 200;
        } else {
            for (int i = 1; i <= 10; i++) {
                if ((progress + 20) / 20 == i) {
                    pro = i * 20;
                    break;
                }
            }
        }
        return pro;
    }

    // 如果超过1024M，就用G表示
    private void calculateTotalOnstarPackage(float totals) {
        tv_flowUnit.setText(R.string.package_flow_behind);
        java.text.DecimalFormat df = new java.text.DecimalFormat("####.##");
        String totalFlow = df.format(totals);
        tv_flowTotal.setText(totalFlow);
    }
}